import _ from 'lodash'
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken, setToken } from '@/utils/auth'
import appConfig from '@/utils/appConfig'

const prefix = _.trim(appConfig.prefix, '/')

const baseURL = '/api/' + (prefix ? prefix + '/' : '')

log(baseURL)

const service = axios.create({
  baseURL,
  timeout: 5000,
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = getToken()
  }
  return config
}, error => {
  Message.error('应用出错了')
  // Do something with request error
  log(error) // for debug
  Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
  response => {
    const token = response.headers.authorization
    if (token) {
      store.commit('SET_TOKEN', token)
      setToken(token)
    }

    const data = response.data
    if (data.msg) {
      let msgType = 'success'
      if (data.status === false) {
        msgType = 'error'
      }

      Message[msgType](data.msg)
    }

    return response
  },
  error => {
    const config = error.config
    const res = error.response
    log('Request Error: ', res)
    switch (res.status) {
      case 401:
        MessageBox.alert('你已被登出，需要重新登录', '已被登出', {
          confirmButtonText: '重新登录',
          type: 'warning',
        }).finally(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()
          })
        })
        break
      case 422: {
        const errors = res.data.errors
        if (config.$form) {
          const fields = config.$form.fields
          _.forIn(errors, (msg, fieldName) => {
            const field = _.find(fields, f => f.prop === fieldName)
            field.validateState = 'error'
            field.validateMessage = (msg instanceof Array) ? msg[0] : msg
          })
        } else {
          _.forIn(errors, (msg) => {
            Message.error((msg instanceof Array) ? msg[0] : msg)
            return false
          })
        }
        break
      }
      case 404:
        !config['no404Msg'] && Message.error('请求的网址不存在')
        break
      default:
        Message.error('服务器出错了')
    }
    return Promise.reject(error)
  },
)

export default service
